<template>
  <div class="spu-detail-container">
    <!-- 加载状态 -->
    <el-skeleton v-if="loading" :rows="5" animated />

    <!-- 错误提示 -->
    <el-alert v-if="errorMsg" title="加载失败" :description="errorMsg" type="error" show-icon closable />

    <!-- 无数据提示 -->
    <el-empty v-if="!loading && !errorMsg && !spuInfo.id" description="暂无数据" />

    <div v-else>
      <el-card class="spu-card" shadow="hover">
        <!-- SPU基本信息 -->
        <template #header>
          <div class="spu-header">
            <el-row>
              <el-col :span="20">
                <h2 class="spu-name">{{ spuInfo.name || '未知商品' }}</h2>
                 <p class="spu-subtitle">{{ spuInfo.sub_title || spuInfo.subTitle || '暂无副标题' }}</p>
              </el-col>
              <el-col :span="4" class="status-tag">
                <el-tag :type="spuInfo.status === 1 ? 'danger' : 'success'">
                  {{ spuInfo.status === 1 ? '已下架' : '已上架' }}
                </el-tag>
              </el-col>
            </el-row>
          </div>
        </template>

        <!-- SPU详情信息 -->
        <el-descriptions column="1" border>
          <el-descriptions-item label="SPU ID">{{ spuInfo.id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="分类ID">{{ spuInfo.category_id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="模板ID">{{ spuInfo.template_id || '无' }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ spuInfo.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="副标题">{{ spuInfo.sub_title || '暂无副标题' }}</el-descriptions-item>
          <el-descriptions-item label="商品描述">
            <div class="description-content">{{ spuInfo.description || '暂无描述' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="spuInfo.status === 1 ? 'danger' : 'success'">
              {{ spuInfo.status === 1 ? '已下架' : '已上架' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(spuInfo.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(spuInfo.updated_at) }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- SKU列表 -->
      <el-card class="sku-card" shadow="hover">
        <template #header>
          <h3>SKU列表</h3>
        </template>

        <div v-if="skuList.length === 0" class="empty-sku">
          <el-icon>
            <InfoFilled />
          </el-icon>
          <span>该SPU暂无SKU</span>
        </div>

        <el-table v-else :data="skuList" border stripe style="width: 100%"
          :header-cell-style="{ 'background-color': '#f5f7fa' }">
          <el-table-column prop="id" label="SKU ID" width="100" />
          <el-table-column prop="code" label="SKU编码" width="150" />
          <el-table-column prop="price" label="销售价" width="100">
            <template #default="scope">{{ '¥' + (scope.row.price || '0') }}</template>
          </el-table-column>
          <el-table-column prop="original_price" label="原价" width="100">
            <template #default="scope">{{ '¥' + (scope.row.original_price || '0') }}</template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" width="100" />
          <el-table-column label="规格信息" min-width="200">
            <template #default="scope">
              <el-tag v-for="(spec, index) in getSpecMap(scope.row)" :key="index" type="info" style="margin-right: 5px">
                {{ spec.name }}: {{ spec.value }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" plain>
                {{ scope.row.status === 0 ? '禁用' : '启用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" width="180">
            <template #default="scope">{{ formatDate(scope.row.updated_at) }}</template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { getSpuWithSkuBySpuId } from '@/api/product/productSpu' // 引入API接口'

// 状态管理
const loading = ref(true)
const errorMsg = ref('')
const spuInfo = reactive({})
const skuList = ref([])
const route = useRoute()

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 解析规格信息为键值对
const getSpecMap = (sku) => {
  // 检查是否有specNameGroup和specValueGroup字段
  if (sku.specNameGroup && sku.specValueGroup) {
    try {
      const names = JSON.parse(sku.specNameGroup)
      const values = JSON.parse(sku.specValueGroup)
      return names.map((name, index) => ({
        name,
        value: values[index] || ''
      }))
    } catch (e) {
      console.error('解析规格信息出错:', e)
      return []
    }
  }
   
  // 如果没有specNameGroup和specValueGroup，尝试从spec_data中解析
  if (sku.spec_data || sku.skuSpecData) {
    try {
      const specDataStr = sku.spec_data || sku.skuSpecData;
      const specData = typeof specDataStr === 'string' ? JSON.parse(specDataStr) : specDataStr;
      if (Array.isArray(specData)) {
        return specData.map(item => ({
          name: item.name || item.key || '未知规格',
          value: item.value || item.val || ''
        }))
      }
    } catch (e) {
      console.error('解析spec_data出错:', e)
    }
  }

  return []
}

// 获取数据
const fetchData = async () => {
  try {
    const spuId = route.params.id // 从路由参数获取SPU ID
    console.log('获取SPU详情，SPU ID:', spuId); // 添加调试日志

    if (!spuId) {
      errorMsg.value = '未提供SPU ID';
      loading.value = false;
      return;
    }

    const res = await getSpuWithSkuBySpuId(spuId)
    console.log('API响应:', res); // 添加调试日志

    if (res.code === 200 && res.data && res.data.length > 0) {
      // 过滤出SPU信息（不包含SKU信息的记录）
      const spuItems = res.data.filter(item =>
        item.name !== null &&
        item.name !== undefined &&
        (item.skuId === null || item.skuId === undefined || item.skuId === 0)
      );

      // 过滤出SKU信息（包含有效SKU信息的记录）
      const skuItems = res.data.filter(item =>
        item.skuId !== null &&
        item.skuId !== undefined &&
        item.skuId !== 0
      );

      console.log('SPU记录:', spuItems);
      console.log('SKU记录:', skuItems);

      // 提取SPU基本信息
      if (spuItems.length > 0) {
        const spuItem = spuItems[0];
        Object.assign(spuInfo, {
          id: spuItem.spuId || spuItem.spu_id || spuId,
          category_id: spuItem.categoryId || spuItem.category_id,
          template_id: spuItem.templateId || spuItem.template_id,
          name: spuItem.name,
          sub_title: spuItem.subTitle || spuItem.sub_title,
          description: spuItem.description,
          status: spuItem.status !== undefined ? spuItem.status : spuItem.skuStatus,
          created_at: spuItem.createdAt || spuItem.created_at,
          updated_at: spuItem.updatedAt || spuItem.updated_at
        });
      } else if (skuItems.length > 0) {
        // 如果没有专门的SPU记录，从SKU记录中提取SPU信息
        const skuItem = skuItems[0];
        Object.assign(spuInfo, {
          id: skuItem.spuId || skuItem.spu_id || spuId,
          category_id: skuItem.categoryId || skuItem.category_id,
          template_id: skuItem.templateId || skuItem.template_id,
          name: skuItem.name,
          sub_title: skuItem.subTitle || skuItem.sub_title,
          description: skuItem.description,
          status: skuItem.status,
          created_at: skuItem.createdAt || skuItem.created_at,
          updated_at: skuItem.updatedAt || skuItem.updated_at
        });
      }

      // 提取SKU列表
      skuList.value = skuItems.map(item => ({
        id: item.skuId,
        code: item.skuCode,
        price: item.skuPrice,
        original_price: item.skuOriginalPrice || item.sku_original_price,
        stock: item.skuStock,
        spec_data: item.skuSpecData,
        specNameGroup: item.specNameGroup,
        specValueGroup: item.specValueGroup,
        status: item.skuStatus,
        updated_at: item.updatedAt || item.updated_at
      }));

      console.log('处理后的SPU信息:', spuInfo);
      console.log('处理后的SKU列表:', skuList.value);
    } else {
      errorMsg.value = '未找到SPU相关数据';
      console.log('未找到SPU相关数据');
    }
  } catch (err) {
    console.error('获取SPU详情出错:', err); // 添加错误日志
    errorMsg.value = err.message || '数据加载失败，请重试';
    ElMessage.error(errorMsg.value);
  } finally {
    loading.value = false;
  }
}

// 页面挂载时加载数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.spu-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.spu-card {
  margin-bottom: 20px;
}

.spu-header {
  padding-bottom: 15px;
  border-bottom: 1px dashed #e5e7eb;
}

.spu-name {
  margin: 0 0 10px 0;
  color: #1f2329;
}

.spu-subtitle {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.status-tag {
  text-align: right;
}

.description-content {
  white-space: pre-wrap;
  line-height: 1.6;
  color: #4b5563;
}

.sku-card {
  margin-top: 20px;
}

.empty-sku {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.empty-sku .el-icon {
  font-size: 24px;
  margin-right: 10px;
  vertical-align: middle;
}

.empty-sku span {
  vertical-align: middle;
}

::v-deep .el-descriptions__cell {
  padding: 12px 16px;
}

::v-deep .el-descriptions__label {
  font-weight: 500;
  color: #4b5563;
}

@media (max-width: 768px) {
  .spu-detail-container {
    padding: 10px;
  }

  .spu-header {
    flex-direction: column;
  }

  .status-tag {
    text-align: left;
    margin-top: 10px;
  }
}
</style>